<!DOCTYPE html>
<html lang="zh">
<head>
  <meta charset="UTF-8">
  <title>Admin - Car Rental</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
  <style>
    body {
      font-family: Arial, sans-serif;
      background-color: #f4f4f4;
    }
    .container { 
      margin-top: 20px;
    }
    h2 { 
      margin-bottom: 20px;
    }
    .card-wrapper {
      width: 95%;
      margin: 0 auto; /* 让其水平居中 */
    }
    .card-custom {
      width: 100%;
      margin: 0 auto;  /* 让其居中 */
      border: none;
      border-radius: 15px;
      box-shadow: 0 4px 12px rgba(0,0,0,0.15);
      transition: all 0.3s ease;
      /* 默认较大 */
      min-height: 600px;
      margin-bottom: 30px;
      position: relative;
    }
    .card-custom:hover {
      box-shadow: 0 6px 16px rgba(0,0,0,0.25);
      transform: scale(1.02);
    }
    .card-custom .card-body {
      padding: 20px;
    }
    .card-custom img {
      width: 100%;
      height: 200px;
      object-fit: contain;
      border-radius: 5px;
      margin-bottom: 10px;
    }
    .car-title {
      font-size: 20px;
      font-weight: bold;
      margin-bottom: 10px;
    }
    .car-details {
      font-size: 18px;
      color: #555;
      margin-bottom: 10px;
      white-space: pre-line;
    }
    textarea {
      width: 100%;
      min-height: 100px;
      margin-bottom: 10px;
      padding: 10px;
      font-size: 14px;
      border: 1px solid #ccc;
      border-radius: 5px;
    }
    textarea:focus {
      border-color: #007bff;
      box-shadow: 0 0 5px rgba(0,123,255,0.5);
      outline: none;
    }
    .delete-button {
      position: absolute;
      top: 10px;
      right: 10px;
      color: #fff;
      cursor: pointer;
    }
    .footer {
      background-color: #0056b3;
      color: #fff;
      text-align: center;
      padding: 20px;
      border-radius: 10px;
      margin-top: 50px;
    }
    /* 新增：多语言输入框的样式 */
    .lang-group {
      margin-top: 10px;
    }
    .lang-group label {
      font-weight: bold;
      margin-top: 10px;
    }
    /* 小屏幕优化 */
    @media (max-width: 768px) {
      .page-wrapper { flex-direction: column; }
      .left-section, .left-section img {
        width: 100%; 
        display: block;
      }
      .right-section { width: 100%; }
    }
  </style>

  <script>
    if (localStorage.getItem('isAdminLoggedIn') !== 'true') {
      window.location.href = 'login.html';
    }
  </script>
</head>

<body>
  <nav class="admin-nav mb-3 text-center">
    <a href="vehicle-admin.html" class="btn btn-primary me-2">车辆管理</a>
    <a href="order-admin.html" class="btn btn-secondary">订单管理</a>
  </nav>

  <div class="container">
    <h2>Admin - Manage Cars</h2>
    <div id="messageArea"></div>
    <div class="mb-3">
      <button id="addCarBtn" class="btn btn-success me-2">
        <i class="fas fa-plus"></i> 加车 add cars
      </button>
      <button id="sortBtn" class="btn btn-primary me-2">
        <i class="fas fa-sort-numeric-down"></i> 排序 order cars
      </button>
      <button id="batchDeleteBtn" class="btn btn-danger">
        <i class="fas fa-trash"></i> 批量删除 batch cars
      </button>
    </div>
    <div class="row" id="carList"></div>
  </div>

  <div class="footer text-center">
    <p>Admin Panel © 2025</p>
  </div>


  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
  <script src="https://widget.cloudinary.com/v2.0/global/all.js"></script>
  <script type="module">
    // 检查登录状态
    if (localStorage.getItem('isAdminLoggedIn') !== 'true') {
      window.location.href = 'login.html';
    }
    import { initializeApp } from "https://www.gstatic.com/firebasejs/9.22.2/firebase-app.js";
    import { getFirestore, doc, getDoc, setDoc, onSnapshot } from "https://www.gstatic.com/firebasejs/9.22.2/firebase-firestore.js";

    const firebaseConfig = {
      apiKey: "YOUR_API_KEY",
      authDomain: "rental-7fe8c.firebaseapp.com",
      projectId: "rental-7fe8c",
      storageBucket: "rental-7fe8c.appspot.com",
      messagingSenderId: "263132536954",
      appId: "1:263132536954:web:55d988d88b1a078b4b9bc3"
    };

    const app = initializeApp(firebaseConfig);
    const db = getFirestore(app);

    let carsData = [];

    function showMessage(message, type = "success") {
      const msgDiv = document.getElementById("messageArea");
      msgDiv.innerHTML = `
        <div class="alert alert-${type} alert-dismissible fade show" role="alert">
          ${message}
          <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>`;
      setTimeout(() => {
        const alert = msgDiv.querySelector(".alert");
        if (alert) alert.remove();
      }, 3000);
    }

    async function uploadToCloudinary(file) {
      const form = new FormData();
      form.append('file', file);
      form.append('upload_preset', 'CarImage');  // 你的 unsigned preset 名
  
      const res  = await fetch(
        'https://api.cloudinary.com/v1_1/dffbcvu4c/image/upload',
        { method: 'POST', body: form }
      );
      const json = await res.json();
      console.log('Cloudinary 返回:', json);
  
      // 云端返回的地址字段可能是 secure_url 或 url
      const url = json.secure_url || json.url;
      if (url) return url;
  
      // 如果都有拿不到，抛出它的 error 信息
      throw new Error(json.error?.message || 'Upload failed');
    }
    // 加载车辆数据
    async function loadData() {
      try {
        const docRef  = doc(db, "cars", "data");
        const docSnap = await getDoc(docRef);
        if (docSnap.exists()) {
          carsData = docSnap.data().cars || [];
        } else {
          carsData = [];
        }
        // ⭐ 在这里确保每个 car.images 是数组
        carsData.forEach(car => {
          if (!Array.isArray(car.images)) {
            car.images = [];
          }
          // 兼容老数据的 text/description
          if (typeof car.text        === "string") car.text        = { zh: car.text,        en: "", th: "" };
          if (typeof car.description === "string") car.description = { zh: car.description, en: "", th: "" };
        });
        renderCars();
      } catch (error) {
        showMessage("Failed to load data: " + error.message, "danger");
      }
    }

    // 实时监听车辆数据更新
    onSnapshot(doc(db, "cars", "data"), docSnap => {
      if (docSnap.exists()) {
        carsData = docSnap.data().cars || [];
      } else {
        carsData = [];
      }
      // ⭐ 同样这里也要保证 images 数组存在
      carsData.forEach(car => {
        if (!Array.isArray(car.images)) {
          car.images = [];
        }
      });
      renderCars();
    });

    // 保存车辆数据
    async function saveData() {
      try {
        const docRef = doc(db, "cars", "data");
        await setDoc(docRef, { cars: carsData });
      } catch (error) {
        showMessage("Failed to save data: " + error.message, "danger");
      }
    }

    function generateUniqueId() {
      return Date.now().toString();
    }

    function addCar() {
      carsData.push({
        id: generateUniqueId(),
        text: { zh: "", en: "", th: "" },
        images: [], // 新增图片数组字段
        description: { zh: "", en: "", th: "" },
        selected: false
      });
      saveData();
      renderCars();
      showMessage("New car added.", "success");
    }

    function deleteCar(index) {
      if (confirm("Are you sure you want to delete this car?")) {
        carsData.splice(index, 1);
        saveData();
        renderCars();
        showMessage("Car deleted.", "success");
      }
    }

    function batchDelete() {
      if (confirm("Delete all selected cars?")) {
        carsData = carsData.filter(car => !car.selected);
        saveData();
        renderCars();
        showMessage("Selected cars deleted.", "success");
      }
    }

    function toggleSelect(index, checkbox) {
      carsData[index].selected = checkbox.checked;
      saveData();
    }

    // 更新车辆文本（多语言）
    function updateText(event, index, lang) {
      if (!carsData[index].text) {
        carsData[index].text = {};
      }
      carsData[index].text[lang] = event.target.value;
      saveData();
    }

    // 更新单张图片 URL
    function updateImageUrl(event, index) {
      carsData[index].image = event.target.value;
      saveData();
      renderCars();
    }

    // 更新车辆描述（多语言）
    function updateDescription(event, index, lang) {
      if (!carsData[index].description) {
        carsData[index].description = {};
      }
      carsData[index].description[lang] = event.target.value;
      saveData();
    }

    // 排序函数（按中文日租价格排序）
    function sortByPrice() {
      carsData.sort((a, b) => {
        const priceA = extractDayPrice(a.text?.zh || "");
        const priceB = extractDayPrice(b.text?.zh || "");
        return priceA - priceB;
      });
      saveData();
      renderCars();
      showMessage("Sorted by day price.", "success");
    }

    function extractDayPrice(text) {
      const match = text.match(/日租：(\d+)/);
      return match ? parseInt(match[1]) : Infinity;
    }

    // 用于在 admin 卡片里生成多张图片的编辑区域
    function renderCarImagesFields(car, carIndex) {
      return `
        <div class="mb-2">
          <button class="btn btn-info btn-sm"
                  onclick="openUploadWidget(${carIndex})">
            批量上传图片
          </button>
        </div>
      `;
    }

    window.openUploadWidget = function(carIndex) {
      const widget = cloudinary.createUploadWidget({
        cloudName: 'dffbcvu4c',         // 你的 cloud_name
        uploadPreset: 'CarImage',       // 你的 unsigned preset
        multiple: true,                 // 允许多文件
        folder: 'car_uploads',          // （可选）统一存到该文件夹
        clientAllowedFormats: ['jpg','png','jpeg']
      }, (error, result) => {
        if (!error && result.event === 'queues-end') {
          // queues-end 事件后，result.info.files 包含所有上传成功文件
          result.info.files.forEach(f => {
            carsData[carIndex].images.push(f.uploadInfo.secure_url);
          });
          saveData().then(renderCars);
          showMessage('批量上传完成', 'success');
        }
      });
      widget.open();  
    };
    

    function renderCars() {
      const carList = document.getElementById("carList");
      carList.innerHTML = "";
      carsData.forEach((car, index) => {
        const textObj = car.text || {};
        const descriptionObj = car.description || {};
        const firstLine = textObj.zh ? textObj.zh.split("\n")[0] : "";
        const restLines = textObj.zh ? textObj.zh.split("\n").slice(1).join("\n") : "";

        const thumbsHtml = (car.images || [])
          .map(url => `
            <img src="${url}"
                class="img-thumbnail me-1 mb-1"
                style="width:80px; height:80px; object-fit:cover; border-radius:8px;">
          `).join("");

        const cardHtml = `
            <div class="col-12 mb-4">
              <div class="card-custom p-3" style="position: relative;">
                <!-- … 其他按钮和输入区 … -->

                <div class="mt-2">
                <label class="form-label">多张图片 (images数组):</label>
                ${renderCarImagesFields(car, index)}
          
                <!-- 新增：缩略图预览 -->
                <div class="mt-2">
                  <label class="form-label">预览：</label>
                  <div class="d-flex flex-wrap">
                    ${thumbsHtml}
                  </div>
                </div>

                <div class="car-title">${firstLine}</div>
                <div class="car-details">${restLines}</div>
              
              <!-- 下面可以加入多语言的编辑区域 -->
              <div class="lang-group mt-3">
                <ul class="nav nav-tabs" id="langTabs_${index}" role="tablist">
                  <li class="nav-item" role="presentation">
                    <button class="nav-link active" data-bs-toggle="tab" data-bs-target="#langZh_${index}" type="button" role="tab">中文</button>
                  </li>
                  <li class="nav-item" role="presentation">
                    <button class="nav-link" data-bs-toggle="tab" data-bs-target="#langEn_${index}" type="button" role="tab">English</button>
                  </li>
                  <li class="nav-item" role="presentation">
                    <button class="nav-link" data-bs-toggle="tab" data-bs-target="#langTh_${index}" type="button" role="tab">ไทย</button>
                  </li>
                </ul>
                <div class="tab-content mt-3" id="langTabsContent_${index}">
                  <div class="tab-pane fade show active" id="langZh_${index}" role="tabpanel">
                    <div class="row">
                      <div class="col-md-6 mb-3">
                        <label class="form-label"><strong>车辆信息 (中文):</strong></label>
                        <textarea class="form-control" rows="4" oninput="updateText(event, ${index}, 'zh')">${textObj.zh || ""}</textarea>
                      </div>
                      <div class="col-md-6 mb-3">
                        <label class="form-label"><strong>描述 (中文):</strong></label>
                        <textarea class="form-control" rows="4" oninput="updateDescription(event, ${index}, 'zh')">${descriptionObj.zh || ""}</textarea>
                      </div>
                    </div>
                  </div>
                  <div class="tab-pane fade" id="langEn_${index}" role="tabpanel">
                    <div class="row">
                      <div class="col-md-6 mb-3">
                        <label class="form-label"><strong>Car Info (English):</strong></label>
                        <textarea class="form-control" rows="4" oninput="updateText(event, ${index}, 'en')">${textObj.en || ""}</textarea>
                      </div>
                      <div class="col-md-6 mb-3">
                        <label class="form-label"><strong>Description (English):</strong></label>
                        <textarea class="form-control" rows="4" oninput="updateDescription(event, ${index}, 'en')">${descriptionObj.en || ""}</textarea>
                      </div>
                    </div>
                  </div>
                  <div class="tab-pane fade" id="langTh_${index}" role="tabpanel">
                    <div class="row">
                      <div class="col-md-6 mb-3">
                        <label class="form-label"><strong>ข้อมูลรถ (ไทย):</strong></label>
                        <textarea class="form-control" rows="4" oninput="updateText(event, ${index}, 'th')">${textObj.th || ""}</textarea>
                      </div>
                      <div class="col-md-6 mb-3">
                        <label class="form-label"><strong>คำอธิบาย (ไทย):</strong></label>
                        <textarea class="form-control" rows="4" oninput="updateDescription(event, ${index}, 'th')">${descriptionObj.th || ""}</textarea>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        `;
        document.getElementById("carList").insertAdjacentHTML("beforeend", cardHtml);
      });
    }

    window.addEventListener("DOMContentLoaded", () => {
      document.getElementById("addCarBtn").addEventListener("click", addCar);
      document.getElementById("sortBtn").addEventListener("click", sortByPrice);
      document.getElementById("batchDeleteBtn").addEventListener("click", batchDelete);

      // 加载数据
      loadData();
    });

    // 将一些函数挂载到全局
    window.deleteCar = deleteCar;
    window.toggleSelect = toggleSelect;
    window.updateText = updateText;
    window.updateImageUrl = updateImageUrl;
    window.updateDescription = updateDescription;
    
  </script>
</body>
</html>